package com.qf.lanzhou.blog.api.controller;

import com.qf.lanzhou.blog.api.pojo.entity.User;
import com.qf.lanzhou.blog.api.service.UserService;
import com.qf.lanzhou.blog.api.service.impl.UserServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Yeach-chen
 * @ClassName SetAdminServlet
 */
@WebServlet("/setAdmin.do")
public class SetAdminServlet extends BaseServletPost {
    private UserService userService= new UserServiceImp();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("设置管理员请求-----------");
        User user = (User) req.getSession().getAttribute("user");
        //获取userId;
        String userI = req.getParameter("userId");
        long userId = Long.decode(userI);
        System.out.println("设置管理员请求-----------111111"+userId);
        if (userService.checkAdmin(user.getId())){
            failedResultWrite("您不是管理员，无权限设置他人为管理员",resp);
            return;
        }
        //判断被添加人是否为管理员
        if (!userService.checkAdmin(userId)){
            failedResultWrite("对方已是管理员，无法添加",resp);
            return;
        }
        if (userService.checkAdminFull()){
            failedResultWrite("管理员人数已达到上限6人，无法添加该用户为管理员",resp);
            return;
        }

        //添加该用户为管理员
        int num;
        System.out.println("开始添加管理员--------------");
        try {
            num = userService.addAdmin(userId);
            successResultWrite(num,resp);
        }catch (RuntimeException e){
            String message = e.getMessage();
            failedResultWrite(message,resp);
        }

    }
}
